local extension = Package("ling8")
extension.extensionName = "lingling"

local U = require "packages/utility/utility"

local getNearBy = function (player)
  return {player:getLastAlive().id, player:getNextAlive().id}
end

local zhuyuanzhang = General(extension, "lingling__zhuyuanzhang", "ming", 4)
local zilei = fk.CreateTriggerSkill{
  name = "lingling__zilei",
  mute = true,
  frequency = Skill.Compulsory,
  events = {fk.TurnEnd, fk.TargetConfirmed, fk.CardUseFinished},
  can_trigger = function (self, event, target, player, data)
    if player:hasSkill(self) then
      if event == fk.TurnEnd then
        return target == player
      elseif event == fk.TargetConfirmed then
        return target == player and data.from ~= player.id and data.card.is_damage_card
      elseif event == fk.CardUseFinished then
        return target ~= player and data.card.is_damage_card and data.damageDealt and data.damageDealt[player.id] and
          table.contains(TargetGroup:getRealTargets(data.tos), player.id)
      end
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    player:broadcastSkillInvoke(self.name)
    if event == fk.TurnEnd then
      room:notifySkillInvoked(player, self.name, "negative")
      room:askForDiscard(player, 2, 2, false, self.name, false)
    else
      room:notifySkillInvoked(player, self.name, "drawcard")
      local n = player:isKongcheng() and 2 or 1
      if event == fk.CardUseFinished then
        n = 1
      end
      player:drawCards(n, self.name)
    end
  end
}
local xiongyi = fk.CreateTriggerSkill{
  name = "lingling__xiongyi",
  anim_type = "big",
  events = {fk.RoundStart},
  can_trigger = function (self, event, target, player, data)
    return player:hasSkill(self) and player.room:getTag("RoundCount") == 8
  end,
  on_cost = function (self, event, target, player, data)
    local room = player.room
    local nearBy = getNearBy(player)
    if #nearBy > 0 then
      local to = room:askForChoosePlayers(player, nearBy, 1, 1, "#lingling__xiongyi-choose", self.name, true)
      if #to == 1 then
        self.cost_data = to
        return true
      end
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    room:damage{
      from = player,
      to = room:getPlayerById(self.cost_data[1]),
      damage = 3,
    }
  end,
}
zhuyuanzhang:addSkill(zilei)
zhuyuanzhang:addSkill(xiongyi)
Fk:loadTranslationTable{
  ["lingling__zhuyuanzhang"] = "朱元璋",
  ["#lingling__zhuyuanzhang"] = "洪武太祖",
  ["designer:lingling__zhuyuanzhang"] = "伶",
  ["illustrator:lingling__zhuyuanzhang"] = "珊瑚虫",
  ["lingling__zilei"] = "自累",
  [":lingling__zilei"] = "回合结束时，你弃置两张手牌。当其他角色使用伤害类牌指定你为目标后，你摸一张牌，若你没有手牌则额外摸一张牌，"..
  "若此牌对你造成伤害，则再摸一张牌。",
  ["lingling__xiongyi"] = "凶疑",
  [":lingling__xiongyi"] = "第八轮开始时，你可以对一名邻家造成3点伤害。"..
  "<br><br> <font color='#a40000'>杀尽江南百万兵，腰间宝剑犹血腥。</font>",
  ["#lingling__xiongyi-choose"] = "凶疑：你可以对一名相邻角色造成3点伤害！",
}

local zhudi = General(extension, "lingling__zhudi", "ming", 5)
local zhengbian = fk.CreateActiveSkill{
  name = "lingling__zhengbian",
  anim_type = "offensive",
  card_num = 0,
  target_num = 1,
  prompt = "#lingling__zhengbian",
  can_use = Util.TrueFunc,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected)
    local to = Fk:currentRoom():getPlayerById(to_select)
    return #selected == 0 and (Self:getLastAlive() == to or Self:getNextAlive() == to)
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    room:damage{
      from = player,
      to = target,
      damage = 1,
      skillName = self.name,
    }
    if not player.dead then
      room:handleAddLoseSkills(player, "-" .. self.name)
    end
    if not target.dead and not target:hasSkill(self, true) then
      room:handleAddLoseSkills(target, self.name)
    end
  end,
}
local huantu = fk.CreateTriggerSkill{
  name = "lingling__huantu",
  anim_type = "drawcard",
  frequency = Skill.Compulsory,
  events = {fk.Damaged},
  on_trigger = function(self, event, target, player, data)
    self.cancel_cost = false
    for i = 1, data.damage do
      if i > 1 and (self.cancel_cost or not player:hasSkill(self)) then return false end
      self:doCost(event, target, player, data)
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local to = player
    if player:usedSkillTimes("lingling__jingnan", Player.HistoryGame) == 0 then
      to = room:askForChoosePlayers(player, getNearBy(player), 1, 1, "#lingling__huantu-choose", self.name, false)
      to = room:getPlayerById(to[1])
    end
    local choice = room:askForChoice(to, {"basic", "trick", "equip"}, self.name, "#lingling__huantu-choice:" .. player.id)
    room:sendLog{
      type = "#HuantuDeclareType",
      from = to.id,
      arg = choice,
    }
    local cid = room:getCardsFromPileByRule(".|.|.|.|.|" .. choice)
    if #cid > 0 then
      if player:hasSkill("lingling__jingnan", true) and player:usedSkillTimes("lingling__jingnan", Player.HistoryGame) == 0 then
        room:addPlayerMark(player, "@lingling__jingnan_record", 1)
      end
      room:obtainCard(player, cid, false, fk.ReasonJustMove, nil, self.name )
    end
  end,
}
local jingnan = fk.CreateTriggerSkill{
  name = "lingling__jingnan",
  frequency = Skill.Wake,
  events = {fk.AfterSkillEffect},
  can_trigger = function (self, event, target, player, data)
    return target == player and player:hasSkill(self) and data.name == "lingling__huantu" and
      player:usedSkillTimes(self.name, Player.HistoryGame) == 0
  end,
  can_wake = function (self, event, target, player, data)
    return player:getMark("@lingling__jingnan_record") > 2
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    room:setPlayerMark(player, "@lingling__jingnan_record", 0)
    room:changeMaxHp(player, -1)
    if player.dead then return end
    if not player:isWounded() then
      player:drawCards(2, self.name)
    else
      local choices = {"draw2", "recover"}
      local choice = room:askForChoice(player, choices, self.name)
      if choice == "recover" then
        room:recover{
          who = player,
          num = 1,
          skillName = self.name
        }
      else
        player:drawCards(2, self.name)
      end
    end
    if player.dead then return end
    room:handleAddLoseSkills(player, "lingling__yongle")
  end,
}
local yongle = fk.CreateViewAsSkill{
  name = "lingling__yongle",
  anim_type = "special",
  prompt = ".",
  interaction = function()
    local all_names = U.getAllCardNames("bt")
    local names = U.getViewAsCardNames(Self, "tea_hongcui", all_names, Self:getCardIds("he"))
    if #names > 0 then
      return U.CardNameBox { choices = names, all_choices = all_names }
    end
  end,
  card_filter = function(self, to_select, selected)
    if not self.interaction.data or #selected > 1 then return end
    local ctype = Fk:cloneCard(self.interaction.data).type
    local to_type = Fk:getCardById(to_select).type
    if ctype == to_type then return end
    if #selected == 1 then
      return to_type ~= Fk:getCardById(selected[1]).type
    end
    return true
  end,
  view_as = function(self, cards)
    if not self.interaction.data or #cards ~= 2 then return end
    local card = Fk:cloneCard(self.interaction.data)
    card.skillName = self.name
    card:addSubcards(cards)
    return card
  end,
  enabled_at_play = function(self, player)
    return true
  end,
  enabled_at_response = function(self, player, response)
    return not response
  end,
}
zhudi:addSkill(zhengbian)
zhudi:addSkill(huantu)
zhudi:addSkill(jingnan)
zhudi:addRelatedSkill(yongle)
Fk:loadTranslationTable{
  ["lingling__zhudi"] = "朱棣",
  ["#lingling__zhudi"] = "永乐大帝",
  ["designer:lingling__zhudi"] = "伶",
  ["illustrator:lingling__zhudi"] = "珊瑚虫",
  ["lingling__zhengbian"] = "征边",
  [":lingling__zhengbian"] = "出牌阶段，你可以对上家或下家造成1点伤害，然后你失去此技能，其获得此技能。",
  ["lingling__huantu"] = "缓图",
  [":lingling__huantu"] = "当你受到1点伤害后，你从牌堆获得一张由你指定的邻家声明类型的牌。",
  ["lingling__jingnan"] = "靖难",
  [":lingling__jingnan"] = "觉醒技，当你因“缓图”累计获得三张牌后，你减1点体力上限，回复1点体力或摸两张牌，“缓图”改为由你声明类型，然后获得“永乐”。",
  ["lingling__yongle"] = "永乐",
  [":lingling__yongle"] = "你可以将两张类型不同的牌当另一种类型的任意牌使用（不能当装备牌和延时锦囊牌）。"..
  "<br><br> <font color='#a40000'>洪武、永乐所行之事，远迈前王。</font>",
  ["#lingling__zhengbian"] = "征边：你可以对上家或下家造成1点伤害，你失去此技能，其获得此技能",
  ["#lingling__huantu-choose"] = "缓图：你可以选择一名邻家，其声明一种类型并令你获得一张该类型的牌",
  ["#lingling__huantu-choice"] = "缓图：%src 令你声明一种类别，令其获得一张此类别的牌",
  ["#HuantuDeclareType"] = "%from 声明了 %arg",
  ["@lingling__jingnan_record"] = "靖难",
}

local liuji = General(extension, "lingling__liuji", "ming", 3)
local tuibei = fk.CreateActiveSkill{
  name = "lingling__tuibei",
  anim_type = "offensive",
  target_filter = Util.FalseFunc,
  card_filter = Util.FalseFunc,
  can_use = function (self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0 and player:getMark("lingling__tuibei_count-turn") < 4
  end,
  on_use = function (self, room, effect)
    local player = room:getPlayerById(effect.from)
    while true do
      if player:getMark("lingling__tuibei_count-turn") > 3 then return end
      if player.dead then return end
      local id = room:getNCards(1, "bottom")[1]
      room:moveCards({
        ids = {id},
        toArea = Card.Processing,
        moveReason = fk.ReasonJustMove,
        skillName = self.name,
        proposer = player.id,
      })
      local use = U.askForUseRealCard(room, player, {id}, ".", self.name, "#lingling__tuibei-use:::" .. Fk:getCardById(id, true):toLogString(), {expand_pile = {id}, bypass_times = true}, true)
      if use then
        room:addPlayerMark(player, "lingling__tuibei_count-turn", 1)
        room:useCard(use)
      else
        room:delay(800)
        room:moveCards({
          ids = {id},
          fromArea = Card.Processing,
          toArea = Card.DiscardPile,
          moveReason = fk.ReasonPutIntoDiscardPile,
        })
        return
      end
    end
  end,
}
local ruliu = fk.CreateTriggerSkill{
  name = "lingling__ruliu",
  anim_type = "special",
  events = {fk.CardUseFinished},
  can_trigger = function (self, event, target, player, data)
    if not player:hasSkill(self) or data.card.type ~= Card.TypeTrick then return end
    if not table.contains(player:getTableMark("@$lingling__ruliu"), data.card.trueName) then
      self.cost_data = 1
      return table.contains(getNearBy(player), target.id) or target == player
    else
      if target == player then
        self.cost_data = 2
        return true
      else
        self.cost_data = 3
        return table.contains(U.getActualUseTargets(player.room, data, event), player.id) and (not data.card:isVirtual() or #(data.card.subcards or {}) > 0)
      end
    end
  end,
  on_cost = function (self, event, target, player, data)
    if self.cost_data == 1 or self.cost_data == 2 then
      return true
    elseif self.cost_data == 3 then
      return player.room:askForSkillInvoke(player, self.name, nil, "#lingling__ruliu-invoke:::" .. data.card:toLogString())
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    if self.cost_data == 1 then
      local mark = player:getTableMark("@$lingling__ruliu")
      table.insertIfNeed(mark, data.card.trueName)
      room:setPlayerMark(player, "@$lingling__ruliu", mark)
    elseif self.cost_data == 2 then
      player:drawCards(2, self.name)
    else
      room:moveCards{
        ids = Card:getIdList(data.card),
        toArea = Card.DrawPile,
        moveReason = fk.ReasonJustMove,
        skillName = self.name,
        drawPilePosition = -1,
        moveVisible = true,
      }
      room:sendLog{
        type = "#RuliuPutCardIntoDrawPile",
        from = player.id,
        card = Card:getIdList(data.card),
      }
    end
  end,
}
liuji:addSkill(tuibei)
liuji:addSkill(ruliu)
Fk:loadTranslationTable{
  ["lingling__liuji"] = "刘基",
  ["#lingling__liuji"] = "济时之器",
  ["designer:lingling__liuji"] = "伶",
  ["illustrator:lingling__liuji"] = "珊瑚虫",
  ["lingling__tuibei"] = "推背",
  [":lingling__tuibei"] = "出牌阶段限一次，你可以亮出牌堆底的牌，然后若你能使用此牌则重复此流程（每回合你至多以此法使用四张牌）。",
  ["#lingling__tuibei-use"] = "推背：你可以使用此 %arg",
  ["lingling__ruliu"] = "如流",
  [":lingling__ruliu"] = "当你和你邻家使用你未记录的锦囊牌结算后，你记录此牌。其他角色对你使用你记录的锦囊牌结算后，你可以将之置于牌堆底。你使用你记录的锦囊牌后摸两张牌。"..
  "<br><br> <font color='#a40000'>三分天下诸葛亮，一统江山刘伯温。</font>",
  ["@$lingling__ruliu"] = "如流",
  ["#lingling__ruliu-invoke"] = "如流：你可以将此 %arg 置于牌堆底",
  ["#RuliuPutCardIntoDrawPile"] = "%from 将 %card 置于牌堆底",
}

--[[
local zhenghe = General(extension, "lingling__zhenghe", "ming", 3)
Fk:loadTranslationTable{
  ["lingling__zhenghe"] = "郑和",
  ["#lingling__zhenghe"] = "三宝太监",
  ["designer:lingling__zhenghe"] = "伶",
  ["illustrator:lingling__zhenghe"] = "珊瑚虫",
}

local yuqian = General(extension, "lingling__yuqian", "ming", 3)
Fk:loadTranslationTable{
  ["lingling__yuqian"] = "于谦",
  ["#lingling__yuqian"] = "两袖清风",
  ["designer:lingling__yuqian"] = "伶",
  ["illustrator:lingling__yuqian"] = "珊瑚虫",
}

local wangshouren = General(extension, "lingling__wangshouren", "ming", 3)
Fk:loadTranslationTable{
  ["lingling__wangshouren"] = "王守仁",
  ["#lingling__wangshouren"] = "龙场悟道",
  ["designer:lingling__wangshouren"] = "伶",
  ["illustrator:lingling__wangshouren"] = "珊瑚虫",
}

local zhuhoucong = General(extension, "lingling__zhuhoucong", "ming", 4)
Fk:loadTranslationTable{
  ["lingling__zhuhoucong"] = "朱厚熜",
  ["#lingling__zhuhoucong"] = "中材之主",
  ["designer:lingling__zhuhoucong"] = "伶",
  ["illustrator:lingling__zhuhoucong"] = "珊瑚虫",
}

local weizhongxian = General(extension, "lingling__weizhongxian", "ming", 3)
Fk:loadTranslationTable{
  ["lingling__weizhongxian"] = "魏忠贤",
  ["#lingling__weizhongxian"] = "九千岁",
  ["designer:lingling__weizhongxian"] = "伶",
  ["illustrator:lingling__weizhongxian"] = "珊瑚虫",
}

local lizicheng = General(extension, "lingling__lizicheng", "qun", 4)
Fk:loadTranslationTable{
  ["lingling__lizicheng"] = "李自成",
  ["#lingling__lizicheng"] = "闯王",
  ["designer:lingling__lizicheng"] = "伶",
  ["illustrator:lingling__lizicheng"] = "珊瑚虫",
}]]

return extension
